<template>
  <div class="login-container" style="background-color: #f0f2f5;">
    <el-form
        label-width="80px"
        class="login-form"
    >
      <img src="@/assets/logo.png" class="loginlogo">
      <el-form-item label="用户名：" prop="username">
        <el-input v-model="username"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password"  @keydown.enter="submitForm" v-model="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">登录后台</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElNotification } from 'element-plus';
import axios from 'axios';
import VueCookies from 'vue-cookies';
import router from "@/router/index.js";
import config from "../../../config/config.js";

const username = ref('');
const password = ref('');

const submitForm = async () => {
  try {
    const response = await axios.post(`${config.apiUrl}/admin/login`, {
      username: username.value,
      password: password.value
    });

    if (response.status === 200) {
      // 登录成功
      const adminToken = response.data.token;
      const expiryDate = new Date();
      expiryDate.setDate(expiryDate.getDate() + 10); // 10天过期
      VueCookies.set('adminToken', adminToken, '10d');

      ElNotification({
        title: '成功',
        message: '登录成功！',
        type: 'success',
        duration: 800
      });
      await router.push('/admin/index');
    } else {
      // 登录失败
      ElNotification({
        title: '登录失败',
        message: response.data.message,
        type: 'error',
        duration: 1200
      });
    }
  } catch (error) {
    console.error('登录错误:', error);
    ElNotification({
      title: '错误',
      message: '登录出错，请稍后再试！',
      type: 'error',
      duration: 1700
    });
  }
};
onMounted(() => {
  const adminToken = VueCookies.get('adminToken'); // 获取 userToken
  if (adminToken) {
    VueCookies.set('activeIndex',1);
    router.push('/admin/index');
    ElNotification({
      message: '已经登录，无需重复登录！',
      type: 'success',
      duration: 1700
    });
  }
});
</script>

<style scoped>
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-form {
  width: 350px;
  text-align: center;
}
.loginlogo{
  width: 170px;
  margin-bottom: 15px;
}
</style>
